package com.hrb.douban.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.hrb.douban.CustomApplication;
import com.hrb.douban.OnItemClickListener;
import com.hrb.douban.R;
import com.hrb.douban.activtity.SearchResultActivity;
import com.hrb.douban.constant.ConstantCode;
import com.hrb.douban.record.SubjectsBean;
import com.hrb.douban.utils.ToastUtil;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class ComingAdapter extends RecyclerView.Adapter<ComingAdapter.Vholder> {

    public static final int TYPE_HEADER = 0;
    public static final int TYPE_NORMAL = 1;
    public static final int TYPE_FOOTER = 2;
    private View mHeaderView;
    private View mFooterView;
    private Context mContext;
    private List<SubjectsBean> subjects;
    private OnItemClickListener mClickListener;

    public void setHeaderView(View headerView) {
        mHeaderView = headerView;
        notifyItemInserted(0);
    }
    public void setFooterView(View footerView) {
        /*ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        footerView.setLayoutParams(params);*/
        mFooterView = footerView;
        notifyItemInserted(getItemCount() - 1);
    }

    @NonNull
    @Override
    public Vholder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
        if (mHeaderView != null && viewType == TYPE_HEADER)
        {
            return new Vholder(mHeaderView);
        }
        if (mFooterView != null && viewType == TYPE_FOOTER)
        {
            return new Vholder(mFooterView);
        }
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_recyclerview, viewGroup, false);
        Vholder vholder = new Vholder(view,mClickListener);
        return vholder;
    }

    private int getRealPosition(RecyclerView.ViewHolder holder) {
        int position = holder.getLayoutPosition();
        return mHeaderView == null ? position : position - 1;
    }


    @Override
    public void onBindViewHolder(@NonNull Vholder vholder, int i) {
        //若果是header 类型直接返回
        if (getItemViewType(i) == TYPE_HEADER) return;
        if (isFooterView(i)||getItemViewType(i)==TYPE_FOOTER) return;
        //根据抛出头部获取真实的位置
        SubjectsBean subjectsBean = subjects.get(getRealPosition(vholder));
        //SubjectsBean subjectsBean = subjects.get(i);
        vholder.comingName.setText(subjectsBean.getTitle());
        boolean first = true;
        vholder.comingCategoryBox.removeAllViews();
        for (String category : subjectsBean.getGenres()) {
            TextView tv = new TextView(CustomApplication.getContext());
            tv.setText(category);
            tv.setTextSize(12);
            tv.setTextColor(CustomApplication.getContext().getResources().getColor(R.color.color_666666));
            tv.setPadding(10, 2, 0, 2);
            tv.setSingleLine(true);
            tv.setBackgroundResource(R.drawable.category_shape);
            if (!first) {
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                lp.setMargins(6, 0, 0, 0);
                tv.setLayoutParams(lp);
            } else {
                first = false;
            }
            tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(mClickListener!=null){
                        String category= ((TextView)v).getText().toString();
                        Intent intent=new Intent(CustomApplication.getContext(),SearchResultActivity.class);
                        intent.putExtra("category",category);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        CustomApplication.getContext().startActivity(intent);
                        //加上此句可以在页面上操作 暂时没有 页面上没有做操作（现在）
                        mClickListener.onCategoryClick(v,category);
                    }
                }
            });
            vholder.comingCategoryBox.addView(tv);
        }
        String rate = "";
        if (subjectsBean.getRating().getAverage() > 0) {
            rate = subjectsBean.getRating().getAverage() + "分";
        } else {
            rate = "暂无评分";
        }
        vholder.comingRate.setText(rate);
        vholder.comingRate.setTextColor(Color.argb(255, 255, 255, 255));
        vholder.comingRate.setBackgroundColor(Color.argb(155, 85, 87, 88));
        Glide.with(CustomApplication.getContext()).load(subjectsBean.getImages().getLarge()).diskCacheStrategy(DiskCacheStrategy.ALL).crossFade() .listener(requestListener).override(270, 400).centerCrop().into(vholder.comingImage);
    }

    @Override
    public int getItemCount() {
        //header 不为空，则 rv 的总 Count 需要 +1（把 Header 加上算一个 item）
       // return mHeaderView == null ? subjects.size() : subjects.size() + 1;
       int count= subjects ==null ? 0:subjects.size();
       if(mHeaderView!=null){
           count++;
       }
        if(mFooterView!=null){
            count++;
        }
        return count;
    }


    public ComingAdapter(List<SubjectsBean> subjects) {
        this.subjects = subjects;
    }

    public ComingAdapter(Context mContext, List<SubjectsBean> subjects) {
        this.mContext = mContext;
        this.subjects = subjects;
    }

    //根据pos返回不同的ItemViewType
    @Override
    public int getItemViewType(int position) {
        if (isHeaderView(position)) {
            return TYPE_HEADER;
        } else if (isFooterView(position)) {
            return TYPE_FOOTER;
        } else {
            return TYPE_NORMAL;
        }
        /*if (mHeaderView == null) return TYPE_NORMAL;
        if (position == 0) return TYPE_HEADER;
        return TYPE_NORMAL;*/
    }
    private boolean haveHeaderView() {
        return mHeaderView != null;
    }

    public boolean haveFooterView() {
        return mFooterView != null;
    }

    private boolean isHeaderView(int position) {
        return haveHeaderView() && position == 0;
    }

    private boolean isFooterView(int position) {
        return haveFooterView() && position == getItemCount() - 1;
    }
    @Override
    public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        RecyclerView.LayoutManager manager=recyclerView.getLayoutManager();
        if(manager instanceof GridLayoutManager){
            final GridLayoutManager gridLayoutManager= ((GridLayoutManager)  manager);
            gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int i) {
                    return getItemViewType(i)==TYPE_HEADER||getItemViewType(i)==TYPE_FOOTER? gridLayoutManager.getSpanCount():1;
                }
            });
        }
    }

    RequestListener requestListener = new RequestListener() {
        @Override
        public boolean onException(Exception e, Object model, Target target, boolean isFirstResource) {
            return false;
        }

        @Override
        public boolean onResourceReady(Object resource, Object model, Target target, boolean isFromMemoryCache, boolean isFirstResource) {
            //Log.e(TAG, "model:" + model + " isFirstResource-ready: " + isFirstResource);
            return false;
        }
    };

    public class Vholder extends RecyclerView.ViewHolder implements View.OnClickListener {
        private OnItemClickListener mListener;// 声明自定义的接口
        @BindView(R.id.coming_image)
        ImageView comingImage;
        @BindView(R.id.coming_name)
        TextView comingName;
        /*@BindView(R.id.coming_category)
        TextView comingCategory;*/
        @BindView(R.id.coming_rate)
        TextView comingRate;
        @BindView(R.id.coming_category_box)
        LinearLayout comingCategoryBox;

        public Vholder(@NonNull View itemView) {
            super(itemView);
            if (itemView == mHeaderView) {
                return;
            }
            if (itemView == mFooterView) {
                return;
            }
            ButterKnife.bind(this, itemView);
        }
        public Vholder(View itemView,OnItemClickListener listener){
            super(itemView);
            if (itemView == mHeaderView) {
                return;
            }
            if (itemView == mFooterView) {
                return;
            }
            ButterKnife.bind(this, itemView);
            mListener=listener;
            comingImage.setOnClickListener(this);
            //itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            if(mListener!=null){
               switch (v.getId()){
                   case R.id.coming_image:
                       mListener.onItemClick(v,getLayoutPosition());
                       break;
                   case R.id.coming_category_box:
                       break;
               }

            }

        }
    }
    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mClickListener = listener;
    }

    //增加数据时
    public void add(List<SubjectsBean> list) {
        int position = subjects.size();
        subjects.addAll(position, list);
        notifyItemInserted(position);
    }

    //刷新数据
    public void refresh(List<SubjectsBean> list) {
        subjects.removeAll(subjects);
        subjects.addAll(list);
        notifyDataSetChanged();
    }

    public List<SubjectsBean> getSubjects() {
        return subjects;
    }

    public View getmHeaderView() {
        return mHeaderView;
    }

    public View getmFooterView() {
        return mFooterView;
    }
}
